package com.mszlu.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Author: Jiang Yizhi
 * @Date: 2022/4/2 7:42 PM
 */
@Component
public class ThreadService {


    /**
     * 期望此操作在线程池执行，不会影响原来的主线程
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        /** 为了在多线程环境下线程安全，还要设置一个条件 有人说这是一个乐观锁，但是我不理解。。。*/
        updateWrapper.eq(Article::getViewCounts, viewCounts);
        /** sql语句类似于 udpate article set view_count = 100 where view_count = 99 and id = 12 */
        articleMapper.update(articleUpdate, updateWrapper);
    }
}
